<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="OrderFormForm">
          <a-row>
						<!-- 隐藏客户id字段 -->
						<!-- <a-col :span="24">
							<a-form-item label="客户id" v-bind="validateInfos.customerId" id="OrderFormForm-customerId" name="customerId">
								<a-input v-model:value="formData.customerId" placeholder="请输入客户id"  allow-clear ></a-input>
							</a-form-item>
						</a-col> -->
						<a-col :span="24">
							<a-form-item label="客户名称" v-bind="validateInfos.customerName" id="OrderFormForm-customerName" name="customerName">
								<a-select
									v-model:value="formData.customerName"
									placeholder="请选择或输入客户名称"
									allow-clear
									show-search
									:filter-option="(input, option) => option.label && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
									@change="handleCustomerChange"
								>
									<a-select-option v-for="customer in customerOptions" :key="customer.id" :value="customer.customerName" :label="customer.customerName">
										{{ customer.customerName }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<!-- 隐藏跟进id字段 -->
						<!-- <a-col :span="24">
							<a-form-item label="跟进id" v-bind="validateInfos.followUpId" id="OrderFormForm-followUpId" name="followUpId">
								<a-input v-model:value="formData.followUpId" placeholder="请输入跟进id"  allow-clear ></a-input>
							</a-form-item>
						</a-col> -->
						<a-col :span="24">
							<a-form-item label="产品类别" v-bind="validateInfos.productType" id="OrderFormForm-productType" name="productType">
								<a-select
									v-model:value="formData.productType"
									placeholder="请选择产品类别"
									:loading="productTypeLoading"
									@change="handleProductTypeChange"
									show-search
									:filter-option="(input, option) => option.label && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
									allow-clear
								>
									<a-select-option v-for="type in productTypeList" :key="type.id" :value="type.id" :label="type.productType">
										{{ type.productType }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="产品名称" v-bind="validateInfos.productName" id="OrderFormForm-productName" name="productName">
								<a-select
									v-model:value="formData.productNameIds"
									mode="multiple"
									placeholder="请选择产品名称（可多选）"
									:max-tag-count="2"
									:max-tag-text-length="10"
									:loading="productNameLoading"
									@change="handleProductNameChange"
									:disabled="!formData.productType"
									allow-clear
									show-search
									:filter-option="(input, option) => option.label && option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0"
								>
									<a-select-option v-for="product in productNameList" :key="product.id" :value="product.id" :label="product.productName">
										{{ product.productName }}
									</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
						<a-col :span="24">
              <a-form-item label="最低价格(元)" v-bind="validateInfos.orderBottom" id="OrderFormForm-orderBottom" name="orderBottom">
                <a-input-number v-model:value="formData.orderBottom" placeholder="请输入最低价格（元）" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
              <a-form-item label="最高价格(元)" v-bind="validateInfos.orderPeak" id="OrderFormForm-orderPeak" name="orderPeak">
                <a-input-number v-model:value="formData.orderPeak" placeholder="请输入最高价格（元）" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
              <a-form-item label="最终价格(元)" v-bind="validateInfos.finalAmount" id="OrderFormForm-finalAmount" name="finalAmount">
                <a-input-number v-model:value="formData.finalAmount" placeholder="请输入最终价格（元）" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="24">
							<a-form-item label="订单状态" v-bind="validateInfos.confirmation" id="OrderFormForm-confirmation" name="confirmation">
								<j-dict-select-tag v-model:value="formData.confirmation" dictCode="confirmation" placeholder="请选择订单状态"  allow-clear />
							</a-form-item>
						</a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate, getCustomerNameAndId, getProductTypes, getProductNameByTypeId } from '../OrderForm.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    customerId: '',
    customerName: '',
    followUpId: '',
    productType: '',      // 产品类别ID
    productTypeName: '',  // 产品类别名称
    productNameIds: [],   // 产品名称ID数组
    productName: [],      // 产品名称数组
    orderBottom: undefined,
    orderPeak: undefined,
    finalAmount: undefined,
    confirmation: '',
  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);

  // 产品类别列表
  const productTypeList = ref<Array<{id: string, productType: string}>>([]);
  // 产品名称列表
  const productNameList = ref<Array<{id: string, productName: string}>>([]);
  // 产品类别加载状态
  const productTypeLoading = ref(false);
  // 产品名称加载状态
  const productNameLoading = ref(false);

  // 客户选项数据
  const customerOptions = ref<Array<{id: string, customerName: string}>>([]);

  // 获取产品类别列表
  const fetchProductTypes = async () => {
    try {
      productTypeLoading.value = true;
      const res = await getProductTypes();
      if (res ) {
        productTypeList.value = res;
      } else {
        productTypeList.value = [];
      }
    } catch (error) {
      console.error('获取产品类别失败:', error);
      createMessage.error('获取产品类别失败');
      productTypeList.value = [];
    } finally {
      productTypeLoading.value = false;
    }
  };

  // 根据产品类别ID获取产品名称列表
  const fetchProductName = async (productTypeId) => {
    if (!productTypeId) {
      productNameList.value = [];
      return;
    }

    try {
      productNameLoading.value = true;
      const res = await getProductNameByTypeId(productTypeId);
      if (res ) {
        productNameList.value = res;
      } else {
        productNameList.value = [];
      }
    } catch (error) {
      console.error('获取产品名称失败:', error);
      createMessage.error('获取产品名称失败');
      productNameList.value = [];
    } finally {
      productNameLoading.value = false;
    }
  };

  // 初始化客户选项数据
  const initCustomerOptions = async () => {
    try {
      const res = await getCustomerNameAndId();
      if (res) {
        customerOptions.value = res;
      }
    } catch (error) {
      console.error('获取客户数据失败:', error);
      createMessage.error('获取客户数据失败');
    }
  };

  // 客户选择变化处理
  const handleCustomerChange = (value: string) => {
    if (value) {
      const selectedCustomer = customerOptions.value.find(customer => customer.customerName === value);
      if (selectedCustomer) {
        formData.customerId = selectedCustomer.id;
      }
    } else {
      formData.customerId = '';
    }
  };

  // 处理产品类别选择变化
  const handleProductTypeChange = (value) => {
    // 清空产品名称列表
    formData.productNameIds = [];
    formData.productName = [];

    // 如果选中了产品类别，获取对应的产品名称
    if (value) {
      const selectedType = productTypeList.value.find(item => item.id === value);
      if (selectedType) {
        // v-model 绑定的是类型ID，名称单独存储
        formData.productType = selectedType.id;
        formData.productTypeName = selectedType.productType;
        fetchProductName(selectedType.id);
      }
    } else {
      productNameList.value = [];
    }
  };

  // 处理产品名称选择变化（多选）
  const handleProductNameChange = (values) => {
    if (values && values.length > 0) {
      // 根据选中的ID获取对应的产品名称
      const selectedProducts = productNameList.value.filter(item => values.includes(item.id));
      const productName = selectedProducts.map(item => item.productName);

      formData.productNameIds = values;
      formData.productName = productName;
    } else {
      formData.productNameIds = [];
      formData.productName = [];
    }
  };
  //表单验证
  const validatorRules = reactive({
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  // 产品名称显示处理（已移除，恢复为数组模式）

  
  /**
   * 新增
   */
  function add() {
    edit({});
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })

      // 特殊处理产品名称数据：确保productName是数组
      if (record.productName) {
        if (typeof record.productName === 'string') {
          try {
            tmpData.productName = JSON.parse(record.productName);
          } catch (e) {
            // 如果解析失败，按逗号分割
            tmpData.productName = record.productName.split(',').map(name => name.trim()).filter(name => name);
          }
        } else if (Array.isArray(record.productName)) {
          tmpData.productName = record.productName;
        } else {
          tmpData.productName = [];
        }
      } else {
        tmpData.productName = [];
      }

      // 处理产品类别和产品名称的回显
      if (record.productType) {
        // 如果有产品类别，需要获取对应的产品名称列表
        tmpData.productType = record.productType;
        tmpData.productTypeName = record.productTypeName || '';
        
        // 如果有产品名称，需要根据产品名称找到对应的ID
        if (tmpData.productName && tmpData.productName.length > 0) {
          // 延迟处理，等待产品名称列表加载完成
          nextTick(() => {
            if (productNameList.value.length > 0) {
              const productIds = [];
              tmpData.productName.forEach(name => {
                const product = productNameList.value.find(p => p.productName === name);
                if (product) {
                  productIds.push(product.id);
                }
              });
              formData.productNameIds = productIds;
            }
          });
        }
      }

      //赋值
      Object.assign(formData, tmpData);
      
      // 如果是编辑模式，根据客户名称设置客户ID
      if (tmpData.customerName) {
        const selectedCustomer = customerOptions.value.find(customer => customer.customerName === tmpData.customerName);
        if (selectedCustomer) {
          formData.customerId = selectedCustomer.id;
        }
      }
    });
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        // 产品名称字段保持数组格式，不转换为字符串
        if (data === 'productName') {
          // 产品名称保持数组格式发送给后端
          continue;
        }

        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }

    // 确保产品类别保存为名称（不是ID），并补齐名称字段
    if (model.productType) {
      const selectedType = productTypeList.value.find((item) => item.id === model.productType);
      if (selectedType) {
        model.productTypeName = selectedType.productType;
        model.productType = selectedType.productType; // 提交时按名称入库
      } else if (model.productTypeName) {
        // 兜底：如果已存在名称，则直接覆盖为名称
        model.productType = model.productTypeName;
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  // 组件挂载时初始化
  onMounted(() => {
    fetchProductTypes();
    initCustomerOptions();
  });

  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
